package com.neolix.watch.weather;

import android.os.AsyncTask;

import com.google.common.io.CharStreams;
import com.google.gson.reflect.TypeToken;
import com.neolix.watch.domain.BaiDuWeatherResult;
import com.neolix.watch.util.Constant;
import com.neolix.watch.util.JsonConverter;
import com.neolix.watch.util.SharedPreferencesUtil;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.InputStream;
import java.io.InputStreamReader;

import static com.neolix.watch.util.SharedPreferencesUtil.saveWeatherInfo;


public abstract class RequestWeatherAsyncTask {
    private RequestTask task;

    public abstract void OnResponse(BaiDuWeatherResult httpResponse);

    public void sendRequest() {
        abort();
        task = new RequestTask();
        task.execute();
    }

    public void stop() {
        if (task != null)
            task.cancel(true);
    }

    public class RequestTask extends AsyncTask<Void, Void, BaiDuWeatherResult> {

        @Override
        protected BaiDuWeatherResult doInBackground(Void... iHttpResps) {
            try {
                String apiUrl = "http://api.map.baidu.com/telematics/v3/weather?location=";
                apiUrl += SharedPreferencesUtil.getCurrentLocation().getLontitude();
                apiUrl += ",";
                apiUrl += SharedPreferencesUtil.getCurrentLocation().getLatitude();
                apiUrl += "&output=json&ak=";
                apiUrl += Constant.BAI_DU_WEATHER_AK;

                HttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(apiUrl);
                HttpResponse response = httpClient.execute(httpGet);
                StatusLine statusLine = response.getStatusLine();
                int statusCode = statusLine.getStatusCode();
                if (statusCode == 200) {
                    HttpEntity entity = response.getEntity();
                    InputStream content = entity.getContent();

                    String responseString = CharStreams.toString(new InputStreamReader(content, Constant.DEFAULT_CHARSET));
                    BaiDuWeatherResult result = JsonConverter.convertJsonToObject(responseString, TypeToken.get(BaiDuWeatherResult.class));
                    saveWeatherInfo(result);
                    return result;

                } else {
                    return null;
                }
            } catch (Exception e) {
                return null;
            }
        }

        @Override
        protected void onPostExecute(BaiDuWeatherResult httpResponse) {
            super.onPostExecute(httpResponse);
            OnResponse(httpResponse);
        }
    }

    private void abort() {
        if (task == null)
            return;

        task.cancel(true);
        task = null;
    }
}
